<template>
  <div class="upload-file">
    <el-upload
    :action="state.uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :file-list="state.fileList"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :auto-upload="false"
      :headers="state.headers"
      class="upload-file-uploader"
      @input="handleImage"
      :data="{
        file:fileUpload
      }"
      ref="fileUploadRef"
      v-if="!disabled"
    >
      <!-- 上传按钮 -->
      <el-button  type="primary">选取图片</el-button>
      <!-- 上传提示 -->
      <template #tip>
          <div class="el-upload__tip" v-if="showTip">
        请上传
        <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
        <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
        的文件
      </div>
      </template>
    
    </el-upload>
    <!-- 文件列表 -->
    <transition-group class="upload-file-list aic" 
    name="el-fade-in-linear" tag="div">
      <div :key="file.url"  class="grid4" 
        style="grid-template-columns: repeat(6,1fr)"
      v-for="(file, index) in 
      state.fileList">
       <imagePreview 
        @remove="handleDelete(index)"
        :src="`${state.baseUrl}${file.url}`" />
       
      </div>
    </transition-group>
    <ComDialog v-model="isShowModal" title="裁剪图片" width="80%">
     <VuePictureCropper

              :boxStyle="{
                width: width,
                height: height,
                backgroundColor: '#f8f8f8',
                margin: 'auto',
              }"
              :img="pic"
              :options="{
                rotatable:true,
                viewMode: 1,
                dragMode: 'crop',
                aspectRatio:aspectRatio,
              }"
              @ready="ready"
            />
      <template #footer>
        <div class="">
          <el-button size="large" @click="handleClose">  取消</el-button>
           <el-button size="large" type="primary"
           @click="clear">  清除</el-button>
          <el-button size="large" type="primary" @click="handleRotate(90)"
          >  顺时针旋转</el-button>
          
    <el-button size="large" type="primary" @click="handleRotate(-90)"
          >  逆时针旋转</el-button>
             
          <el-button size="large" type="primary" @click="submitData"
            >保存</el-button
          >
        </div>
      </template>
    </ComDialog>
     
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import {
  shallowRef,
  reactive,
  defineEmits,
  onBeforeMount,
  onMounted,
  watch,
  computed,
  ref,
  PropType,
} from "vue";
import { getToken } from "/@ts/hooks/cookie";
import { ElLoading } from "element-plus";
import imagePreview from '/@/components/ImagePreview/index.vue';
import VuePictureCropper, { cropper } from 'vue-picture-cropper'
const state: any = reactive({
        number: 0,
      uploadList: [],
      baseUrl:import.meta.env.VITE_BASE_URL ,
      uploadFileUrl: import.meta.env.VITE_BASE_URL + "/common/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
});
let visible = shallowRef(false);
const rotateValue = shallowRef(0)
const pic = ref("")
const emit = defineEmits(["update:modelValue"]);
const prop = defineProps({
  modelValue: {
    type: [String, Object, Array],
    
  },
   // 数量限制
    limit: {
      type: Number,
      default:2
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp']
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    // 禁用组件（仅查看文件）
    disabled: {
      type: Boolean,
      default: false
    },
		// 标题宽度
		width: {
			type: String as PropType<string>,
			default: "800px"
		},
		// 标题宽度
		height: {
			type: String as PropType<string>,
			default: "600px"
		},
    aspectRatio: {
      type: Number,
      default:16/10
    }
});
/**
 * 判断文件后缀类型 是否是 图片
 * @param fileName 文件名
 * @returns boolean
 */
const isImage = (fileName: string): boolean => {
  // 图片格式
  const imageTypes = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'];
  // 获取文件后缀
  const extension = fileName.split('.').pop()?.toLowerCase();
  // 判断是否是图片格式
  return extension ? imageTypes.includes(extension) : false;
};

watch(
  () => prop.modelValue,
  (val: any) => {
     if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : val.split(',');
          // 然后将数组转为对象数组
          state.fileList = list.map(item => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          state.fileList = [];
          return [];
        }
  },
  {
    deep: true,
    immediate: true,
  },
);
const loadingInstance = ref()
const isShowModal = shallowRef(false)
const fileName = shallowRef("")
const handleClose = () => {
  isShowModal.value = false
}
    /**
     * Clear the crop box
     */
    function clear() {
      if (!cropper) return
      cropper.clear()
    }
let fileUpload = ref()

const handleRotate = (val) =>{
  cropper.rotate(val)
}
const submitData = async() => {
      if (!cropper) return
     
      handleClose()
            const file = await cropper.getFile({
        fileName:fileName.value,
      })
    fileUpload.value = file
    fileUploadRef.value!.submit()
     
    
    }
    const handleImage = (e)=>{
       const { files } = e.target as HTMLInputElement
      if (!files || !files.length) return

      // Convert to dataURL and pass to the cropper component
      const file = files[0]
        const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        pic.value = String(reader.result)
        isShowModal.value = true

      }
    }
const handleBeforeUpload = (file) => {
    console.log('handleBeforeUpload :>> ');
       // 校检文件类型
      if (prop.fileType) {
        const fileName = file.name.split('.');
        
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = prop.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
            ElMessage({ message: `文件格式不正确，请上传${prop.fileType.join("/")}格式文件!`, type: "error" });
          return false;
        }
      }
      fileName.value = file.name
      // 校检文件名是否包含特殊字符
      if (file.name.includes(',')) {
         ElMessage({ message:'文件名不正确，不能包含英文逗号!', type: "error" });
        return false;
      }
      // 校检文件大小
      if (prop.fileSize) {
        const isLt = file.size / 1024 / 1024 < prop.fileSize;
        if (!isLt) {
          ElMessage({ message:`上传文件大小不能超过 ${prop.fileSize} MB!`, type: "error" });
          return false;
        }
      }
       loadingInstance.value = ElLoading.service({
    lock: true,
    text: "正在上传文件，请稍候...",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
      state.number++;
      return true;
};
const handleUploadError = () => {
  ElMessage({ message:"上传文件失败，请重试", type: "error" });
    loadingInstance.value.close()
};
const uploadedSuccessfully = () =>{
    if (state.number > 0 && state.uploadList.length === state.number) {
        state.fileList = state.fileList.concat(state.uploadList);
        state.uploadList = [];
        state.number = 0;
      
         emit("update:modelValue", listToString(state.fileList));
         loadingInstance.value.close()
      }
}
const fileUploadRef = ref()
const getFileName = (name)=>{
   if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
}
const handleExceed = () => {
  ElMessage({ message:`上传文件数量不能超过 ${prop.limit} 个!`, type: "error" });
};
const showTip = computed(() => {
  return prop.isShowTip && (prop.fileSize || prop.fileType);
});
const handleUploadSuccess = (res, file) => {
  console.log('handleUploadSuccess :>> ');
        if (res.code === 200) {
        state.uploadList.push({ name: res.fileName, url: res.fileName });
       uploadedSuccessfully();
      } else {
        state.number--;
        loadingInstance.value.close()
          ElMessage({ message:res.msg, type: "error" });
       fileUploadRef.value.handleRemove(file);
        uploadedSuccessfully();
      }
};
const listToString = (list, separator?) => {
        let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
};
const handleDelete = (index) => {
  if(!prop.disabled){
        state.fileList.splice(index, 1);
        emit("update:modelValue", listToString(state.fileList));
  }else{
      ElMessage({ message:'禁止删除', type: "error" });
  }
     
};
const handleClear = () => {
  emit("update:modelValue", "");
}
const handleIcon = (name: string) => {
  emit("update:modelValue", name);
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list{
  margin-bottom: 10px;
  display: flex;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

</style>
